package com.t3.anistory
{
	import com.t3.client.T3Client;
	import com.t3.display.StageObject;
	import com.t3.events.StoryEvent;
	import com.t3.sound.CustomClient;
	import com.t3.tuio.*;
	
	import flash.display.Sprite;
	import flash.events.KeyboardEvent;
	import flash.events.NetStatusEvent;
	import flash.events.SecurityErrorEvent;
	import flash.geom.Rectangle;
	import flash.media.Microphone;
	import flash.net.*;

	public class AniStory extends StageObject 
	{
		[Embed(source='/book.swf')]
		private static var Book:Class;
		private static var IDS:uint = 0;
		
		private var _sketchbook:Sketchbook;
		private var _notebook:Notebook; 
		private var _book:Sprite;
		
		private var nc:NetConnection;
		private var ns:NetStream;
		private var stream:NetStream;
		private var mic:Microphone;
		
		private var recordName:String = "";
		
		private var _isRecording:Boolean = false;
		
		public var ID:uint = IDS++; 

		public function AniStory()
		{
        	mic = Microphone.getMicrophone();

			nc = new NetConnection();
			nc.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            nc.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
            nc.connect("rtmp://localhost/tttFiles");
			
			// setup some simple settings with the cam and mic for quality
			setupMic();
			
			// we store the last saved recording so we can play it back when stop is clicked
			var recordName:String = "";

			_book = new Book();
			_book.x = ( T3Client._width - _book.width ) / 2;
			_book.y = ( T3Client._height - _book.height ) / 4;
			
			_notebook = new Notebook( new Rectangle( _book.x + 50, _book.y + 10, 340, 550 ) );
			_sketchbook = new Sketchbook( new Rectangle( _book.x + 470, _book.y + 10, 400, 600 ) );
		
			this.addChild( _book );
			this.addChild( _notebook );
			this.addChild( _sketchbook );
		}
		
		public function keyDown( event:KeyboardEvent ):void
		{
			switch(event.charCode)
			{
				case 32: // spacebar
					sketchbook.startAnimation();
					break;
				case 13: // enter
					sketchbook.startPointAnimation();
					break;
				case 115: //s
					this.startRecord();
					break;
				case 116: //t
					this.stopRecord();
					break;
				case 112: //p
					this.playLastRecord();
					break;
				default:
					break;
			}
		}
		
		private function netStatusHandler(event:NetStatusEvent):void
		{
            switch (event.info.code) 
            {
                case "NetConnection.Connect.Success":
                    connectStream();
                    trace("Connection Success");
                    break;
                case "NetStream.Play.StreamNotFound":
                    trace("Stream not found: ");
                    break;
            }
        }
        private function connectStream():void
        {
            stream = new NetStream(nc);
            stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
            stream.client = new CustomClient();
			openMic();
        }
        
        public function openMic():void
		{
			startRecord();
			stopRecord();
		}

        private function securityErrorHandler(event:SecurityErrorEvent):void
        {
            //trace("securityErrorHandler: " + event);
        }
		
		public function get sketchbook():Sketchbook
		{
			return _sketchbook;
		}
		
		public function get notebook():Notebook
		{
			return _notebook;
		}
		
		public function startRecord():void
		{
			_isRecording = true;
			
			if( mic != null && stream != null )
			{
				stream.attachAudio(mic);
				// create a random number to store a unique name TODO
				recordName = "tttRecord_" + T3Client.waslijn.pageID;
				stream.publish(recordName, "record");
			}
			
			sketchbook.startRecording();
		}
		
		public function storyChanged( event:StoryEvent ):void
		{
			if( event.story != this )
			{
				if( sketchbook.animating )
				{
					sketchbook.stopAnimation();
				}
				
				stopRecord();
			}
		}
		
		public function get isRecording():Boolean
		{
			return _isRecording;
		}
		
		public function stopRecord():void
		{
			_isRecording = false;
			// close the netStream object
			
			if( stream != null )
			{
				stream.close();
			}
			
			if( sketchbook.recording )
			{
				sketchbook.stopRecording();
			}
		}
		
		public function startAnimation():void
		{
			sketchbook.startAnimation();
			playLastRecord();
		}
		
		public function playLastRecord():void
		{
			// play back the recorded stream
			
			if( stream != null )
			{
				stream.play(recordName);
			}
		}

		private function setupMic():void
		{
			// setup mic
			mic = Microphone.getMicrophone();
			//mic.setRate(44);
		}
	}
}